<template>
  <div class="create-project">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>创建新项目</h2>
          <p class="description">配置您的项目信息和部署设置</p>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 步骤导航 -->
      <div class="steps-nav">
        <div 
          v-for="(step, index) in steps" 
          :key="step.key"
          class="step-item"
          :class="{ 
            active: currentStep === index,
            completed: currentStep > index 
          }"
          @click="goToStep(index)"
        >
          <div class="step-number">
            <i v-if="currentStep > index" class="fas fa-check"></i>
            <span v-else>{{ index + 1 }}</span>
          </div>
          <div class="step-info">
            <div class="step-title">{{ step.title }}</div>
            <div class="step-desc">{{ step.description }}</div>
          </div>
        </div>
      </div>

      <!-- 表单内容 -->
      <div class="form-container">
        <el-form 
          ref="formRef"
          :model="form"
          :rules="rules"
          label-position="top"
          class="project-form"
          :validate-on-rule-change="false"
        >
          <!-- 步骤1：基本信息 -->
          <div v-show="currentStep === 0" class="step-content">
            <div class="form-section">
              <h3>项目信息</h3>
              <el-form-item label="项目名称" prop="name">
                <el-input 
                  v-model="form.name" 
                  placeholder="输入项目名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item label="项目描述" prop="description">
                <el-input 
                  v-model="form.description" 
                  type="textarea" 
                  :rows="3"
                  placeholder="描述你的项目..."
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="Git仓库" prop="repositoryUrl">
                <el-input 
                  v-model="form.repositoryUrl" 
                  placeholder="https://github.com/username/repo.git"
                >
                  <template #prepend>
                    <el-select v-model="repoType" style="width: 100px">
                      <el-option label="GitHub" value="github">
                        <i class="fab fa-github"></i> GitHub
                      </el-option>
                      <el-option label="GitLab" value="gitlab">
                        <i class="fab fa-gitlab"></i> GitLab
                      </el-option>
                      <el-option label="Gitee" value="gitee">
                        <i class="fab fa-git-alt"></i> Gitee
                      </el-option>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </div>

            <div class="form-section">
              <h3>快速配置</h3>
              <div class="template-grid">
                <div 
                  v-for="template in templates" 
                  :key="template.key"
                  class="template-card"
                  :class="{ active: selectedTemplate === template.key }"
                  @click="applyTemplate(template.key)"
                >
                  <img :src="template.icon" :alt="template.name" class="template-icon">
                  <div class="template-info">
                    <h4>{{ template.name }}</h4>
                    <p>{{ template.description }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 步骤2：部署配置 -->
          <div v-show="currentStep === 1" class="step-content">
            <div class="form-section">
              <h3>构建配置</h3>
              <el-form-item label="部署分支" prop="deploymentConfig.branch">
                <el-input 
                  v-model="form.deploymentConfig.branch" 
                  placeholder="master"
                >
                  <template #append>
                    <el-button @click="fetchBranches">
                      <i class="fas fa-sync"></i>
                      刷新
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="构建命令" prop="deploymentConfig.buildCommand">
                <el-input 
                  v-model="form.deploymentConfig.buildCommand" 
                  placeholder="npm run build"
                >
                  <template #append>
                    <el-select v-model="form.deploymentConfig.buildCommand" style="width: 150px">
                      <el-option value="npm run build" label="npm run build" />
                      <el-option value="yarn build" label="yarn build" />
                      <el-option value="pnpm build" label="pnpm build" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="输出目录" prop="deploymentConfig.outputDir">
                <el-input 
                  v-model="form.deploymentConfig.outputDir" 
                  placeholder="dist"
                >
                  <template #append>
                    <el-select v-model="form.deploymentConfig.outputDir" style="width: 120px">
                      <el-option value="dist" label="dist" />
                      <el-option value="build" label="build" />
                      <el-option value="public" label="public" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </div>

            <div class="form-section">
              <h3>环境变量</h3>
              <div class="env-vars">
                <div v-for="(env, index) in envVars" :key="index" class="env-var-item">
                  <el-input v-model="env.key" placeholder="KEY" />
                  <el-input v-model="env.value" placeholder="VALUE" />
                  <el-button type="danger" circle @click="removeEnvVar(index)">
                    <i class="fas fa-times"></i>
                  </el-button>
                </div>
                <el-button type="primary" plain @click="addEnvVar">
                  <i class="fas fa-plus"></i>
                  添加环境变量
                </el-button>
              </div>
            </div>
          </div>

          <!-- 步骤3：服务器配置 -->
          <div v-show="currentStep === 2" class="step-content">
            <div class="form-section">
              <h3>服务器信息</h3>
              <el-form-item label="服务器地址" prop="deploymentConfig.serverConfig.host">
                <el-input 
                  v-model="form.deploymentConfig.serverConfig.host" 
                  placeholder="例如：123.456.789.0"
                />
              </el-form-item>

              <el-form-item label="SSH端口" prop="deploymentConfig.serverConfig.port">
                <el-input-number 
                  v-model="form.deploymentConfig.serverConfig.port" 
                  :min="1"
                  :max="65535"
                  :controls="true"
                  :precision="0"
                  placeholder="22"
                />
              </el-form-item>

              <el-form-item label="用户名" prop="deploymentConfig.serverConfig.username">
                <el-input 
                  v-model="form.deploymentConfig.serverConfig.username" 
                  placeholder="root"
                />
              </el-form-item>

              <el-form-item label="认证方式">
                <el-radio-group v-model="form.deploymentConfig.serverConfig.authType">
                  <el-radio :value="'password'">
                    <i class="fas fa-key"></i>
                    密码认证
                  </el-radio>
                  <el-radio :value="'privateKey'">
                    <i class="fas fa-file-alt"></i>
                    SSH密钥
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <template v-if="form.deploymentConfig.serverConfig.authType === 'password'">
                <el-form-item label="密码" prop="deploymentConfig.serverConfig.password">
                  <el-input 
                    v-model="form.deploymentConfig.serverConfig.password"
                    type="password"
                    show-password
                    placeholder="输入服务器密码"
                  />
                </el-form-item>
              </template>

              <template v-else>
                <el-form-item label="SSH私钥" prop="deploymentConfig.serverConfig.privateKey">
                  <el-input 
                    v-model="form.deploymentConfig.serverConfig.privateKey"
                    type="textarea"
                    :rows="8"
                    placeholder="-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----"
                  />
                </el-form-item>
                <el-form-item label="密钥密码（如果有）">
                  <el-input 
                    v-model="form.deploymentConfig.serverConfig.passphrase"
                    type="password"
                    show-password
                    placeholder="可选"
                  />
                </el-form-item>
              </template>

              <el-form-item label="部署路径" prop="deploymentConfig.serverConfig.path">
                <el-input 
                  v-model="form.deploymentConfig.serverConfig.path" 
                  placeholder="/var/www/html"
                />
              </el-form-item>

              <div class="server-actions">
                <el-button 
                  type="primary" 
                  plain 
                  @click="testConnection"
                  :loading="testing"
                >
                  <i class="fas fa-plug"></i>
                  测试连接
                </el-button>
              </div>

              <div v-if="connectionTestResult" 
                   :class="['test-result', connectionTestResult.success ? 'success' : 'error']">
                <i :class="connectionTestResult.success ? 'fas fa-check-circle' : 'fas fa-times-circle'"></i>
                {{ connectionTestResult.message }}
              </div>
            </div>
          </div>

          <!-- 步骤控制按钮 -->
          <div class="form-actions">
            <el-button 
              v-if="currentStep > 0" 
              @click="prevStep"
            >
              <i class="fas fa-arrow-left"></i>
              上一步
            </el-button>
            <el-button 
              type="primary" 
              v-if="currentStep < steps.length - 1" 
              @click="nextStep"
            >
              下一步
              <i class="fas fa-arrow-right"></i>
            </el-button>
            <el-button 
              type="primary" 
              v-if="currentStep === steps.length - 1"
              @click="handleSubmit"
              :loading="creating"
            >
              <i class="fas fa-check"></i>
              创建项目
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { projectApi } from '../api/project'

// 导入项目模板图标
import vueIcon from '@/assets/vue-logo.svg'
import reactIcon from '@/assets/react-logo.svg'
import nodeIcon from '@/assets/node-logo.svg'

const router = useRouter()
const formRef = ref(null)
const currentStep = ref(0)
const repoType = ref('github')
const selectedTemplate = ref('')
const creating = ref(false)
const testing = ref(false)
const connectionTestResult = ref(null)
const envVars = ref([])

// 步骤配置
const steps = [
  {
    key: 'basic',
    title: '基本信息',
    description: '设置项目的基本信息'
  },
  {
    key: 'deploy',
    title: '部署配置',
    description: '配置构建和环境变量'
  },
  {
    key: 'server',
    title: '服务器配置',
    description: '配置部署服务器'
  }
]

// 项目模板配置
const templates = [
  {
    key: 'vue',
    name: 'Vue.js',
    description: '适用于 Vue.js 项目',
    icon: vueIcon,
    config: {
      buildCommand: 'npm run build',
      outputDir: 'dist'
    }
  },
  {
    key: 'react',
    name: 'React',
    description: '适用于 React 项目',
    icon: reactIcon,
    config: {
      buildCommand: 'npm run build',
      outputDir: 'build'
    }
  },
  {
    key: 'node',
    name: 'Node.js',
    description: '适用于 Node.js 项目',
    icon: nodeIcon,
    config: {
      buildCommand: 'npm install --production',
      outputDir: '.'
    }
  }
]

// 表单数据
const form = reactive({
  name: '',
  description: '',
  repositoryUrl: '',
  deploymentConfig: {
    branch: 'master',
    buildCommand: 'npm run build',
    outputDir: 'dist',
    serverConfig: {
      host: '',
      port: 22,
      username: '',
      authType: 'password',
      password: '',
      privateKey: '',
      passphrase: '',
      path: ''
    }
  }
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  repositoryUrl: [
    { required: true, message: '请输入Git仓库地址', trigger: 'blur' },
    { 
      pattern: /^(https?:\/\/|git@).*\.git$/,
      message: '请输入有效的Git仓库地址',
      trigger: 'blur'
    }
  ],
  'deploymentConfig.branch': [
    { required: true, message: '请输入部署分支', trigger: 'blur' }
  ],
  'deploymentConfig.buildCommand': [
    { required: true, message: '请输入构建命令', trigger: 'blur' }
  ],
  'deploymentConfig.outputDir': [
    { required: true, message: '请输入输出目录', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.host': [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.username': [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.path': [
    { required: true, message: '请输入部署路径', trigger: 'blur' }
  ]
};

// 应用模板配置
const applyTemplate = (templateKey) => {
  const template = templates.find(t => t.key === templateKey)
  if (template) {
    selectedTemplate.value = templateKey
    form.deploymentConfig.buildCommand = template.config.buildCommand
    form.deploymentConfig.outputDir = template.config.outputDir
  }
}

// 环境变量操作
const addEnvVar = () => {
  envVars.value.push({ key: '', value: '' })
}

const removeEnvVar = (index) => {
  envVars.value.splice(index, 1)
}

// 获取分支列表
const fetchBranches = async () => {
  // TODO: 实现获取分支列表的逻辑
  ElMessage.info('获取分支列表功能开发中...')
}

// 测试服务器连接
const testConnection = async () => {
  try {
    testing.value = true
    connectionTestResult.value = null
    const result = await projectApi.testServerConnection(form.deploymentConfig.serverConfig)
    connectionTestResult.value = result
    ElMessage.success('连接测试成功')
  } catch (error) {
    connectionTestResult.value = {
      success: false,
      message: error.response?.data?.message || '连接测试失败'
    }
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 验证当前步骤的表单字段
const validateStep = async (step) => {
  if (!formRef.value) return true;

  const stepFields = {
    0: ['name', 'description', 'repositoryUrl'],
    1: ['deploymentConfig.branch', 'deploymentConfig.buildCommand', 'deploymentConfig.outputDir'],
    2: ['deploymentConfig.serverConfig.host', 'deploymentConfig.serverConfig.username', 'deploymentConfig.serverConfig.path']
  };

  try {
    let valid = true;
    // 只验证当前步骤的字段
    await formRef.value.validate((isValid, fields) => {
      if (!isValid) {
        // 检查是否当前步骤的字段有错误
        const currentStepFields = stepFields[step];
        const hasErrorInCurrentStep = Object.keys(fields || {}).some(field => 
          currentStepFields.some(stepField => field === stepField)
        );
        if (hasErrorInCurrentStep) {
          valid = false;
        }
      }
    });
    return valid;
  } catch (error) {
    console.error('表单验证失败:', error);
    return false;
  }
};

// 下一步
const nextStep = async () => {
  try {
    const isValid = await validateStep(currentStep.value);
    if (isValid) {
      currentStep.value++;
    } else {
      ElMessage.warning('请填写必要的信息');
    }
  } catch (error) {
    console.error('步骤切换失败:', error);
    ElMessage.error('表单验证失败');
  }
};

// 上一步
const prevStep = () => {
  currentStep.value--;
};

// 跳转到指定步骤
const goToStep = (index) => {
  // 只允许回到之前的步骤
  if (index < currentStep.value) {
    currentStep.value = index;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      creating.value = true;
      
      // 添加环境变量到表单数据
      const envVarsObj = {};
      envVars.value.forEach(({ key, value }) => {
        if (key && value) {
          envVarsObj[key] = value;
        }
      });
      
      const projectData = {
        ...form.value,
        env: envVarsObj
      };
      
      const project = await projectApi.createProject(projectData);
      ElMessage.success('项目创建成功');
      router.push(`/project/${project._id}`);
    }
  } catch (error) {
    console.error('创建项目失败:', error);
    ElMessage.error(error.response?.data?.message || '创建项目失败');
  } finally {
    creating.value = false;
  }
};
</script>

<style scoped>
.create-project {
  min-height: 100vh;
  background: var(--background-primary);
}

.page-header {
  background: var(--background-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: var(--spacing-lg) var(--spacing-xl);
  margin-bottom: var(--spacing-2xl);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.header-left h2 {
  margin-bottom: var(--spacing-xs);
}

.description {
  color: var(--text-secondary);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-xl);
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: var(--spacing-2xl);
}

.steps-nav {
  position: sticky;
  top: var(--spacing-2xl);
}

.step-item {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.step-item:hover {
  background: var(--background-tertiary);
}

.step-item.active {
  background: var(--primary-light);
}

.step-item.completed {
  color: var(--success-color);
}

.step-number {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--background-secondary);
  border-radius: var(--radius-full);
  font-weight: var(--font-weight-medium);
}

.step-item.active .step-number {
  background: var(--primary-color);
  color: white;
}

.step-item.completed .step-number {
  background: var(--success-color);
  color: white;
}

.step-title {
  font-weight: var(--font-weight-medium);
  margin-bottom: var(--spacing-xs);
}

.step-desc {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.form-container {
  background: var(--background-secondary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-2xl);
  box-shadow: var(--shadow-sm);
}

.form-section {
  margin-bottom: var(--spacing-2xl);
}

.form-section h3 {
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
  font-size: var(--font-size-lg);
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-md);
}

.template-card {
  padding: var(--spacing-lg);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.template-card:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
}

.template-card.active {
  border-color: var(--primary-color);
  background: var(--primary-light);
}

.template-icon {
  width: 48px;
  height: 48px;
  margin-bottom: var(--spacing-md);
}

.template-info h4 {
  margin-bottom: var(--spacing-xs);
}

.template-info p {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.env-vars {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.env-var-item {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
}

.server-actions {
  margin-top: var(--spacing-lg);
}

.test-result {
  margin-top: var(--spacing-md);
  padding: var(--spacing-md);
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.test-result.success {
  background: var(--success-color);
  color: white;
}

.test-result.error {
  background: var(--error-color);
  color: white;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  margin-top: var(--spacing-2xl);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--border-color);
}

@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .steps-nav {
    position: static;
    margin-bottom: var(--spacing-xl);
  }
}
</style> 